<template>
  <div class="dashboard-container">
    <meta name="referrer" content="no-referrer" />
    <div class="app-container">
      <el-card shadow="never">
        <!-- 导航 -->
        <el-row>
          <!-- 搜索表单——S -->
          <el-col :span="16" class="nev_left">
            <el-form ref="form" :model="q" label-width="80px" inline>
              <el-form-item label="关键字">
                <el-input v-model="q.keyword" placeholder="根据文章标题搜索" size="small"></el-input>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="q.state" placeholder="请选择" size="small">
                  <el-option label="启用" value="1" size="small"></el-option>
                  <el-option label="禁用" value="0" size="small"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="clearForm" size="small">清除</el-button>
                <el-button type="primary" @click="onSubmit" size="small">搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8" class="nev_right">
            <el-button type="success" size="small" @click="newSkills"><i class="el-icon-edit"></i>新增技巧</el-button>
          </el-col>
          <!-- 搜索表单——E -->
        </el-row>
        <!-- 数据统计条数显示--S -->
        <el-row>
          <el-col :span="24" class="totalInfo">
            <i class="el-icon-info"></i>
            <span>数据一共{{ total }}条</span>
          </el-col>
        </el-row>
        <!-- 数据统计条数显示--E -->
        <!-- 表格主体--S -->
        <el-table :data="skiList" border style="width: 100%">
          <el-table-column type="index" label="序号" width="80px"> </el-table-column>
          <el-table-column prop="title" label="文章标题" width="400px">
            <template slot-scope="{ row }">
              <div class="articleTitle">
                {{ row.title }}
                <i v-if="row.videoURL" @click="videoPre(row.videoURL)" class="el-icon-film"></i>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="visits" label="阅读数"> </el-table-column>
          <el-table-column prop="username" width="120px" label="录入人"> </el-table-column>
          <el-table-column prop="createTime" width="160px" label="录入时间">
            <template slot-scope="{ row }">
              <div>
                {{ formatTime(row.createTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态">
            <template slot-scope="{ row }">
              <div>
                {{ row.state === 1 ? '已启用' : '已禁用' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="180px" label="操作">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="preview(row)">预览</el-button>
              <el-button type="text" size="small" @click="switchBan(row)">
                {{ row.state === 1 ? '禁用' : '启用' }}
              </el-button>
              <template v-if="!row.state">
                <el-button @click="edit(row)" type="text" size="small">修改</el-button>
                <el-button @click="artDelete(row.id)" type="text" size="small">删除</el-button>
              </template>
              <template v-else>
                <el-button type="text" size="small" disabled>修改</el-button>
                <el-button type="text" size="small" disabled>删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格主体--E -->
        <!-- 分页功能--S -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          :current-page="page"
          :page-sizes="pagesizes"
          :page-size="pagesize"
          :total="total"
          layout="prev, pager, next, sizes, jumper"
        >
        </el-pagination>
        <!-- 分页功能--E -->
      </el-card>
      <!-- 视频弹层 -->
      <el-dialog
        class="videoPre"
        fullscreen
        :before-close="videoClose"
        :modal="false"
        :visible.sync="videoDialog"
        ref="videoPefDiao"
      >
        <div>
          视频
          <video src="" ref="videoRef" autoplay></video>
        </div>
      </el-dialog>
      <!-- 预览弹层 -->
      <ArticlePre :artPreDiao.sync="artPreDiao" :artData="artData"></ArticlePre>
      <!-- 添加文章弹窗 -->
      <ArticleAdd
        ref="addDiao"
        :addDiao.sync="addDiao"
        :artData.sync="artData"
        @updataList="getArticleList"
      ></ArticleAdd>
    </div>
  </div>
</template>

<script>
// 时间格式化插件
import moment from 'moment'
// API 接口导入
import { list, changeState, remove } from '@/api/hmmm/articles.js'
export default {
  name: 'Articles',
  data() {
    return {
      // 查询的参数对象
      q: {
        keyword: '',
        state: ''
      },
      // ------页码相关
      // 当前页码
      page: 1,
      // 页尺寸
      pagesize: 10,
      // 页尺寸合集
      pagesizes: [5, 10, 15, 20],
      // 列表数据
      skiList: [],
      // 文章数据总量
      total: 12,
      // -----------------------视频弹层相关
      videoDialog: false,
      // -------------------------预览弹层相关
      // 预览层的显示隐藏
      artPreDiao: false,
      // 传入的文章数据
      artData: '',
      // -----------------------添加和修改层相关
      // 层的显示和隐藏
      addDiao: false
    }
  },
  created() {
    this.getArticleList()
  },
  components: {
    // 文章预览组件
    ArticlePre: () => import('@/module-hmmm/components/articles-preview.vue'),
    // 文章修改和添加组件
    ArticleAdd: () => import('@/module-hmmm/components/articles-add.vue')
  },
  methods: {
    // --------------------导航栏相关
    // 清除表单数据操作
    clearForm() {
      // 清除 q 参数对象数据
      for (const key in this.q) {
        this.q[key] = ''
      }
      this.getArticleList()
    },
    // 提交表单操作
    onSubmit() {
      if (!this.q.keyword && !this.q.state) return
      this.getArticleList(true)
    },
    // 新增技巧
    newSkills() {
      this.addDiao = true
    },
    // ----------------------分页功能相关
    // 切换显示数据量
    handleSizeChange(size) {
      this.pagesize = size
      this.getArticleList()
    },
    // 页数跳转
    handleCurrentChange(page) {
      this.page = page
      this.getArticleList()
    },
    // ---------------------获取文章列表
    async getArticleList(isSubmit = false) {
      let data = {}
      if (isSubmit) {
        // 结构数据组装为 data
        const { keyword, state } = this.q
        // 判断是否为空
        data = { keyword, state, page: this.page, pagesize: this.pagesize }
        if (!keyword) delete data.keyword
        if (!state) delete data.state
      } else {
        data = { page: this.page, pagesize: this.pagesize }
      }
      try {
        const { data: res } = await list(data)
        // 信息注入
        this.total = res.counts
        this.skiList = res.items
      } catch (error) {
        console.log(error)
      }
    },
    // -----------------------------格式化时间
    formatTime(time) {
      const res = new Date(time)
      return moment(res).format('YYYY-MM-DD HH:mm:ss')
    },
    // -------------------------视频预览
    videoPre(url) {
      // 对 URL 地址进行判断
      const reg = /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i
      if (reg.test(url)) {
        // 在显示效果结束后播放视频
        this.videoDialog = true
        this.$refs.videoPefDiao.$nextTick(() => {
          this.$refs.videoRef.src = url
        })
      } else {
        this.$message.error('视频地址错误！')
      }
    },
    // 关闭视频后停止播放
    videoClose() {
      this.videoDialog = false
      this.$refs.videoRef.pause()
    },
    // ------------------------------操作列
    // 预览键
    preview(content) {
      this.artPreDiao = true
      this.artData = content
    },
    // 启用和禁用
    async switchBan(data) {
      try {
        const { id, state } = data
        // 发送请求
        const { data: res } = await changeState({ id, state: +!state })
        // 提示
        if (res.success) {
          this.$message.success('操作成功')
        }
        // 修改数据列表中的数据
        this.skiList.forEach(item => {
          if (item.id === id) {
            item.state = +!item.state
          }
        })
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 编辑
    edit(data) {
      // 传入数据
      this.artData = data
      // 打开面板
      this.addDiao = true
      // 调用数据回填功能
      this.$nextTick(function() {
        this.$refs.addDiao.dataInit()
      })
    },
    // 删除
    artDelete(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // -------确认删除
          try {
            await remove({ id })
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            if (this.skiList.length === 1 && this.page > 1) this.page--
            this.getArticleList()
          } catch (error) {
            this.$message.error(error)
          }
        })
        .catch(error => {
          // -------取消删除
          console.log(error)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.nev_left {
  .el-input {
    width: 221px;
  }
}
.nev_right {
  .el-button {
    float: right;
  }
  .el-icon-edit {
    margin-right: 10px;
  }
}
.totalInfo {
  background-color: #f4f4f5;
  color: #909399;
  padding: 10px 12px;
  font-size: 14px;
  border-radius: 5px;
  i {
    margin-right: 10px;
  }
}
.el-pagination {
  float: right;
  margin: 10px;
}
.el-table {
  margin-top: 20px;
}
.articleTitle {
  i {
    float: right;
    color: #409eff;
    font-size: 20px;
    cursor: pointer;
  }
}
.videoPre {
  ::v-deep .el-dialog__header {
    background-color: rgba($color: #000000, $alpha: 0);
    position: relative;
  }
  ::v-deep .el-dialog {
    border-radius: 0;
    background-color: rgba(0, 0, 0, 0.3);
    .el-dialog__headerbtn {
      width: 50px;
      height: 50px;
      margin: 30px;
      background-color: rgba(0, 0, 0, 0.4);
      box-shadow: 0 0 5px rgb(0 0 0 / 40%);
      text-align: center;
      line-height: 50px;
      border-radius: 50%;
      font-size: 20px;
      left: 50%;
      transform: translate(-50%);
    }
  }
  video {
    margin-top: 70px;
    position: absolute;
    left: 50%;
    transform: translate(-50%);
    width: 60%;
  }
}
</style>
